package com.ms.p2p.controller.app;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.exception.NoticeException;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.CommonUtil;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.entity.RetMap;
import com.ms.p2p.entity.UserThreadLocal;
import com.ms.p2p.entity.account.Account;
import com.ms.p2p.entity.loan.Loan;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.entity.redpacket.RedPacket;
import com.ms.p2p.enums.LoanStatus;
import com.ms.p2p.plugin.validation.annotation.RequiredStringValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import com.ms.p2p.provider.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chensk on 2018/3/15.
 */
@Controller
@RequestMapping({ "/api" })
public class ApiLoanController extends  BaseController{



    @Reference
    private LoanProvider loanProvider;
    @Reference
    private MemberAccountProvider memberAccountProvider;

    @Reference
    EvcProvider evcProvider;
    @Reference
    private LoanStayProvider loanStayProvider;

    @Reference
    private MemberProvider memberProvider;
    @Reference
    private LoanTenderRecordProvider loanTenderRecordProvider;
    @Reference
    private CertiFiCationProvider certificationProvider;

    @Reference
    private PasswordProvider passwordProvider;
    @Reference
    private LoanCategoryProvider loanCategoryProvider;
    @Reference
    private RedPacketProvider redPacketProvider ;

    /**
     * 标的列表 loanCategory类型
     *
     */
    @RequestMapping({"/loan/list"})
    @ResponseBody
    public HashMap loanAjax(
            @RequestParam(value = "currentPage", required = false) Integer currentPage,

            @RequestParam(value = "loanCategory", required = false) Integer loanCategory

    ){

        PageBean borrowPage = new PageBean();
        if (currentPage != null) {
            borrowPage.setCurrentPage(currentPage);
        }  if("".equals(loanCategory)){
            loanCategory = null;
        }

        List<Map<String, Object>> borrows = null;
        borrows = loanProvider.findPager(null, null, null, loanCategory, null, null, null, null, null, null, null, null, null, null, borrowPage);
        borrowPage.setTotalCount(loanProvider.findCount(null, null, null, loanCategory, null, null, null, null, null, null, null, null, null, null));
        for( Map<String, Object> map:borrows){
            map.put("pics",loanProvider.findImgByBorrowId(Integer.parseInt(map.get("id").toString())));

        }
        HashMap retMap = RetMap.Success("获取数据成功");
        retMap.put("page",borrowPage);
        retMap.put("list",borrows);

        return  retMap;


    }
    @RequestMapping({"/member/loan/red/list"})
    @ResponseBody
    public HashMap redlist(Integer currentPage,Integer time_limit){
        Member member = UserThreadLocal.get();

        PageBean page = new PageBean();
        page.setCurrentPage(currentPage);
        List<RedPacket>redpackets =redPacketProvider.findPager(page,"0",member.getId(),time_limit);
        HashMap retMap = RetMap.Success("获取数据成功");
        retMap.put("list",redpackets);
        return  retMap;


    }




    @Autowired
    private ServletContext applicationScope;
    /**
     * 标的详情
     */
    @RequestMapping({"/loan/detail"})
    @ResponseBody
    public HashMap toLoanDetail(String loanId, Model model) {
        Loan loan = loanProvider.findById(loanId);
        HashMap map = RetMap.Success("获取成功");
        loan.pics.addAll(loanProvider.findImgByBorrowId(Integer.parseInt(loan.getId().toString())));

        map.put("item",loan);
        return  map;
    }
    /**
     * 标的详情
     */
    @RequestMapping({"/loan/tenderlist"})
    @ResponseBody
    public HashMap tenderlist(String loanId, Model model) {
        HashMap map = RetMap.Success("获取成功");
        map.put("list",loanTenderRecordProvider.findTenders(Integer.parseInt(loanId)));
        return  map;
    }

    /**
     * 投标
     * packet_id 红包id
     * loanId 标的id
     * tbpwd 投标定向密码
     *
     *
     */
    @RequestMapping("/member/loan/tender")
    @ResponseBody
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "payPassword", message = "支付密码不能为空"),
            @RequiredStringValidator(fieldName = "account", message = "金额不能为空")

    })
    public HashMap tender(String token, Double account, String payPassword,
                          String loanId, String tbpwd, HttpServletRequest request, HttpSession session, String packet_id)
            throws Exception {
        Member member = UserThreadLocal.get();
        String returnMsg = "投标成功";

        // 查询实名认证状态
        String retmsg = certificationProvider.getCertiStatus(member.getId());
        if (StringUtils.isNotBlank(retmsg)) {
            throw new NoticeException(retmsg);
        }
        if (!passwordProvider.checkPayPwd(member.getId(), DigestUtils.md5Hex(payPassword))) {
            throw new NoticeException("交易密码错误");
        }

        // 获取用户的投标金额
        if (account == null || account < 0) {
            throw new NoticeException("投标金额小于0");

        }
        Loan loan = loanProvider.findById(loanId);

        if (loan.getUser_id().equals(member.getId())) {
            throw new NoticeException("不能投自己的标！");
        }
        Account userAccount = memberAccountProvider.findByUserId(member.getId());
        if (userAccount.getBalance().compareTo(
                new BigDecimal(request.getParameter("account"))) == -1) {
            throw new NoticeException("余额不足，请充值！");
        }
        if (loan.getStatus() != LoanStatus.STATUS_3.getValue()) {
            throw new NoticeException( "借款标不在可投资状态");
        }
//        if (loan.getLoan_category() == 8 && !loan.getPassword().equals(member.getUser_name())) {
//            throw new NoticeException("您不是该标的的约标用户");
//        }
//        if (StringUtils.isNotBlank(loan.getTbpwd()) && !loan.getTbpwd().equals(tbpwd)) {
//            throw new NoticeException("定向密码错误");
//        }

        double lastmoney = loan.getAccount().subtract(loan.getAmount_invested()).setScale(2, 4).doubleValue();
        double amontInforce = account;// 有效金额
        if (lastmoney < account) {
            amontInforce = lastmoney;
            returnMsg = "投标成功,您的有效金额为：" + amontInforce;
        }
        if (amontInforce <= 0.0D) {
            throw new NoticeException("此标已满!");
        }
        if (loan.getLoan_category() == 1) {
            loanTenderRecordProvider.doRookie(member, loan);
        }
        if (loan.getLoan_category() == 10 && userAccount.getCollection().compareTo(loan.getLowest_wait_account()) < 0) {
            throw new NoticeException("金额小于最小待收要求");
        }
        // 不因为数据库延迟出错
        BigDecimal successAmount = new BigDecimal(amontInforce).setScale(2, 4);
        loanProvider.doTender(successAmount, loan, member, account, AppContext.getRemoteIp(), packet_id);
        return RetMap.Success(returnMsg);
    }


}
